package com.video.main_video.common.utils;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import java.io.File;
import java.io.IOException;
import java.util.Optional;

public class VideoUtils {
    public static void main(String[]args) throws Exception {
//        String imagePath=extract("G:\\JavaProject\\cut_video\\cda19e64a3fd473eb099e764fff761d3\\11-02-2023\\CHINADJ.mp4","./test");
//        System.out.println(imagePath);
        File file = new File("./test.png");
        file.delete();

//        String s = ImgUtils.compressImageByFile(new File(imagePath));
//
//        System.out.println(s);


    }
    /**
     * 提取主方法
     *
     * @param path   MP4视频路径
     * @param tmpDir 临时目录
     * @return 视频第一帧
     * @throws Exception 异常
     */
    public static String extract(String path, String tmpDir) throws Exception {
        return ffmpegExtractImage(path, tmpDir + ".png")
                .orElseThrow(() -> new Exception("提取失败"));
    }

    /**
     * 提取视频第一帧图片
     *
     * @param mp4Path 视频地址
     * @param picPath 图片地址
     * @return 提取的图片地址
     */
    public static Optional<String> ffmpegExtractImage(String mp4Path, String picPath) throws FFmpegFrameGrabber.Exception {
        ProcessBuilder extractBuilder =
                new ProcessBuilder(
                        "ffmpeg", "-i", mp4Path, "-f", "image2", "-ss", "1", "-frames:v", "1", picPath,"-y");
        try {
            extractBuilder.inheritIO().start().waitFor();
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
            return Optional.empty();
        }
        // 返回图片文件路径
        return Optional.of(picPath);
    }

//    删除文件
    public static boolean deleteFile(String path){
        File file = new File(path);
        if (file.delete()){
            return true;
        }
        return false;
    }
}
